<template>
    <view>
        <u-popup v-model="showInfo" mask :safeAreaInsetBottom="true" border-radius="14" mode="bottom"
                 @close="showInfo = false">
            <view :style="{marginBottom: `${botNavHei}rpx`}" class="bd-model"
                  style="width: 750upx;display:block"
                  @touchmove.stop.prevent>
                <view class="form-info dir-top-nowrap">
                    <view class="form-head box-grow-0 dir-left-nowrap cross-center main-between">
                        <view>总计</view>
                        <image src="/static/image/icon/close.png" @click="showInfo = false"></image>
                    </view>
                    <view style="padding:20rpx 24rpx;font-size:30rpx">
                        <view style="color:#333333;margin-bottom: 24rpx">基础价格</view>
                        <view class="dir-left-nowrap main-between cross-center">
                            <view class="dir-left-nowrap cross-center" @click="showItemInfo = !showItemInfo">
                                <view style="color:#999999">商品价格</view>
                                <view :style="{transform: showItemInfo?  'rotate(180deg)' : 'rotate(0deg)'}"
                                      class="showItemInfo dir-left-nowrap cross-center main-center">
                                    <view></view>
                                    <view></view>
                                </view>
                            </view>
                            <view style="color:#FF4544">￥{{ goodsPrice }}</view>
                        </view>
                    </view>
                    <view v-if="showItemInfo" class="calc-box">
                        <scroll-view class="scroll-view calc-swiper" enhanced scroll-with-animation
                                     scroll-y
                                     style="max-height: calc(41vh - 72px);">
                            <view v-for="(item,index) of allData" :key="index" class="calc-box-item">
                                <view v-for="(i,index2) in item" :key="index2"
                                      :index="index2" class="calc-box-c dir-left-nowrap main-between cross-center">
                                    <view>{{ i.label }}</view>
                                    <view>{{ i.value }}</view>
                                </view>
                            </view>
                        </scroll-view>
                    </view>
                </view>
            </view>
        </u-popup>
        <view :style="[boxStyle]" class="dir-left-nowrap cross-center main-between form-fixed">
            <view class="dir-left-nowrap cross-bottom">
                <view v-show="calcError" style="color: #FF4544;font-size: 22rpx;max-width: 264rpx">
{{ErrorMsg}}
                </view>
                <view v-show="!calcError" class="dir-left-nowrap cross-bottom">
                    <view style="font-size: 32rpx;line-height: 1;margin-bottom: 2px">￥</view>
                    <view style="font-size: 52rpx;line-height:1">{{ calcPrice }}</view>
                </view>
            </view>
            <view class="dir-left-nowrap cross-center">
                <view class="dir-left-nowrap cross-center" @click="showInfo = !showInfo">
                    <view class="button-info">明细</view>
                    <view :style="{transform: showInfo?  'rotate(0deg)' : 'rotate(180deg)'}"
                          class="jiantou dir-left-nowrap cross-center main-center">
                        <view></view>
                        <view></view>
                    </view>
                </view>
                <view :style="[btnStyle]" class="main-center cross-center" @click="afterSubmit">
                    {{ data.btn_title }}
                </view>
            </view>
        </view>
    </view>

</template>

<script>
import appModel from '../../components/basic-component/app-model/app-model.vue';
import formValue from '../../components/page-component/diy-form/formValue.js';
import {mapGetters} from "vuex";
import uPopup from "../../components/basic-component/u-popup/u-popup.vue";
import formCalc from './form-calc.js';

export default {
    name: 'diy-form-button',
    mixins: [formCalc],
    props: {
        value: Object,
        otherForm: Array,
        formId: [Number, String],
        pageId: [Number, String],
    },
    components: {appModel, uPopup,},

    data() {
        return {
            showItemInfo: true,
            showInfo: false,
            data: {},
            scrollTopNum: 1,

            secondModel: false,
            clickSubmit: false,

            allData: [],
            goodsPrice: '',
        }
    },

    computed: {
        calcPrice() {
            return this.handlerCalcPrice();
        },
        ...mapGetters('iPhoneX', {
            botNavHei: 'getNavHei',
        }),
        boxStyle() {
            if (!this.data) return {};
            let {
                bg_color,
                input_padding,
                limit_color,
                total_color,
            } = this.data;
            return {
                backgroundColor: bg_color,
                paddingLeft: `${input_padding}rpx`,
                paddingRight: `${input_padding}rpx`,
                paddingBottom: `env(safe-area-inset-bottom)`,
                height: `calc(${this.botNavHei}rpx + env(safe-area-inset-bottom))`,
                color: total_color,
                borderTop: `1px solid ${limit_color || bg_color}`,
            }
        },
        btnStyle() {
            if (!this.data) return {};
            let {
                btn_text_color,
                padding_color,
                border_color,
                btn_radius,
            } = this.data;
            return {
                color: btn_text_color,
                backgroundColor: padding_color,
                padding: '0 58rpx',
                height: '68rpx',
                lineHeight: '1',
                border: `1px solid ${border_color || padding_color}`,
                borderRadius: `${btn_radius}rpx`,
                opacity: this.calcError ? '0.5': 1,
            }
        },
    },
    created() {
        this.origin = 'form-button'
    },
    mounted() {
        this.data = this.value;
        this.goodsPrice = this.FloatMul(this.goodsForm.options.price, this.goodsForm.options.stock);
        this.allData = this.contentFormat();
    },

    methods: {
        toExchange() {
            let {goods_id, stock, date, mch_list, attr_groups} = this.goodsForm.options;
            mch_list = JSON.parse(mch_list);
            Object.assign(mch_list[0], {date, stock})
            if (mch_list[0].mch_id) {
                Object.assign(mch_list[0], {mch_id: mch_list[0].mch_id})
            } else {
                Object.assign(mch_list[0], {mch_id: 0})
            }

            let url = `/pages/order-submit/order-submit?mch_list=${JSON.stringify(mch_list)}`;
            url += `&preview_url=${encodeURIComponent(this.$api.order.form_order_preview)}&submit_url=${encodeURIComponent(this.$api.order.form_order_submit)}`;
            if (this.goodsForm.mch_id) {
                url += `&plugin=mch`;
            }
            uni.navigateTo({url})
        },

        handleSubmit() {
            uni.showLoading({
                mask: true
            });
            this.secondModel = false;
            let form = new formValue({
                key: 'form-button',
                label: this.data.title,
                value: {},
                required: 0
            });
            form.add({unique: this.data.key || ''});
            let form_data = [].concat(this.goodsForm.otherForm, form.getObject());

            form_data = form_data.map(_ => {
                let {hideIds, hideIdsStatus} = this.goodsForm;
                Object.assign(_, {is_hide: 0});
                if ([].concat(hideIds, hideIdsStatus).indexOf(_.unique) !== -1) {
                    //_.value = null;
                    Object.assign(_, {is_hide: 1});
                }
                return _;
            })
            const {goods_id,mch_list} = this.goodsForm.options;

            let para = {
                goods_id: goods_id,
                mch_id: JSON.parse(mch_list)[0].mch_id,
                form_data: JSON.stringify(form_data),
            }
            this.$request({
                url: this.$api.order.goods_form,
                data: para,
                method: 'POST',
            }).then(response => {
                uni.hideLoading();
                this.clickSubmit = false;
                if (response.code === 0) {
                    this.toExchange();
                } else {
                    uni.showToast({title: response.msg, icon: 'none'});
                }
            }).catch(response => {
                this.clickSubmit = false;
                uni.hideLoading();
            });
        },
        FloatMul(arg1, arg2) {
            var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
            try {
                m += s1.split(".")[1].length
            } catch (e) {
            }
            try {
                m += s2.split(".")[1].length
            } catch (e) {
            }
            let number = Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
            return Number(number.toString().match(/^\d+(?:\.\d{0,2})?/))
        },
        afterSubmit() {
            if (this.clickSubmit || this.calcError) return false

            this.goodsForm.testSubmit()
            if (this.goodsForm.error) {
                uni.showToast({title: this.goodsForm.error, icon: 'none'});
                return false;
            }
            this.clickSubmit = true
            this.$subscribe(this.goodsForm.template_message_list).then(res => {
                this.handleSubmit()
            }).catch(() => {
                this.handleSubmit()
            });
        },
        contentFormat() {
            let allData = [];
            const {goods_id, stock, date, mch_list, attr_groups} = this.goodsForm.options;
            ///
            let attrValue = [];
            for (let i of JSON.parse(mch_list)[0].goods_list[0].attrs) {
                for (let j of JSON.parse(attr_groups)) {
                    if (i.attr_group_id == j.attr_group_id) {
                        for (let k of j.attr_list) {
                            if (i.attr_id == k.attr_id) {
                                attrValue.push({
                                    label: j.attr_group_name,
                                    value: k.attr_name
                                })
                            }
                        }
                    }
                }
            }
            if (attrValue.length) allData.push(attrValue)
            ////
            let date_data = [];
            const p_date = JSON.parse(date);
            if (p_date.data.length) {
                date_data = date_data.concat([{
                    label: '预约时间',
                    value: '',
                }], p_date.data.map(item => {
                    return {
                        label: Object.keys(item)[0],
                        value: '￥' + item[Object.keys(item)[0]],
                    }
                }));
                allData.push(date_data);
            }

            ////
            allData.push([{
                label: '数量',
                value: stock,
            }])
            ///
            return allData;
        },
    },
}
</script>

<style lang="scss" scoped>
.showItemInfo {
    margin-right: 30#{rpx};
    margin-left: 18#{rpx};
    margin-top: 4#{rpx};

    > view {
        height: 21#{rpx};
        width: 2#{rpx};
        background: #c0c4cc;
    }

    > view:first-child {
        transform: rotate(-45deg);
    }

    > view:last-child {
        margin-left: 12#{rpx};
        transform: rotate(45deg);
    }
}


.calc-box {
    border-radius: 10#{rpx};
    background: #f6f6f6;
    margin: 0 14#{rpx} 30#{rpx};
    color: #999999;
    font-size: 28#{rpx};

    .calc-swiper {
        .calc-box-item {
            padding: 10#{rpx} 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .calc-box-item:last-child {
            border-bottom-width: 0;
        }

        .calc-box-c {
            width: 100%;
            padding: 10#{rpx};
        }

    }

}


.form-fixed {
    position: fixed;
    bottom: 0;
    background: white;
    width: 100%;
    z-index: 2001;

    .button-info {
        font-size: 28#{rpx};
        color: #999999;
    }

    .jiantou {
        margin-right: 30#{rpx};
        margin-left: 18#{rpx};
        margin-top: 4#{rpx};

        > view {
            height: 21#{rpx};
            width: 4#{rpx};
            background: #c0c4cc;
        }

        > view:first-child {
            transform: rotate(-45deg);
        }

        > view:last-child {
            margin-left: 8#{rpx};
            transform: rotate(45deg);
        }
    }
}

.form-info {
    width: 100%;
    bottom: 110#{rpx};

    .form-head {
        background: #FFFFFF;
        border-radius: 16#{rpx} 16#{rpx} 0 0;
        height: 95#{rpx};
        width: 100%;
        padding: 0 24#{rpx};
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);

        > view {
            font-size: 38#{rpx};
            color: #333333;
        }

        > image {
            width: 28#{rpx};
            height: 28#{rpx};
            display: block;
        }
    }

}
</style>
